package pl.enigmatic.reflection;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;


public class Methods {

	/** method to add an object into a collection */
	public final static Method add;
	/** method to add a collection of objects into a collection */
	public final static Method addAll;
	/** method to add an object into a collection */
	public final static Method put;
	/** method to add a collection of objects into a collection */
	public final static Method putAll;

	static {
		Method method = null;
		try {
			method = Collection.class.getMethod("add", new Class<?>[] { Object.class });
		} catch (final Exception e) {}
		add = method;
		method = null;
		try {
			method = Collection.class.getMethod("addAll", new Class<?>[] { Collection.class });
		} catch (final Exception e) {}
		addAll = method;
		method = null;
		try {
			method = Map.class.getMethod("put", new Class<?>[] { Object.class, Object.class });
		} catch (final Exception e) {}
		put = method;
		method = null;
		try {
			method = Map.class.getMethod("putAll", new Class<?>[] { Map.class });
		} catch (final Exception e) {}
		putAll = method;
	}

	public static boolean add(final Object collection, final Object item) {
		try {
			add.invoke(collection, item);
			return true;
		} catch (final Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public static boolean addAll(final Object collection, final Object items) {
		try {
			addAll.invoke(collection, items);
			return true;
		} catch (final Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public static boolean put(final Object map, final Object key, final Object value) {
		try {
			put.invoke(map, key, value);
			return true;
		} catch (final Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public static boolean putAll(final Object map, final Object key, final Object itemsMap) {
		try {
			putAll.invoke(map, itemsMap);
			return true;
		} catch (final Exception e) {
			e.printStackTrace();
		}
		return false;
	}

}
